const express = require('express')
const morgan = require('morgan')
const path = require('path')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const session = require('express-session')
const FileStore = require('session-file-store')(session)
const favicon = require('serve-favicon')
const expressStaticGzip = require('express-static-gzip')
const app = express()
const staticPath = 'public'
const routes = require('./app/routes/index')
/*const config = require('./config/config.json')*/
const port = process.env.PORT || 3000
//const proxy = require('express-http-proxy')
const env = process.env.NODE_ENV
const AV = require('leanengine')

AV.init({
  appId: process.env.LEANCLOUD_APP_ID || 'ij7U5LTyuyofIKPsPwznzMfr-gzGzoHsz',
  appKey: process.env.LEANCLOUD_APP_KEY || 'lubv1dObVhnowG0tAq2Iy7am',
  masterKey: process.env.LEANCLOUD_APP_MASTER_KEY || 'Tom7wunKJpt2Yf4nM5OUv7jX'
});

process.env.TZ = 'Asia/Shanghai'
app.set('trust proxy', 1) // trust first proxy
app.use(favicon(path.join(__dirname, 'src', 'images', 'logo.png')))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
app.use(session({
  secret: 'adafd!Dds143',
  store: new FileStore(),
  resave: true,
  saveUninitialized: true,
  cookie: {maxAge: 1000 * 60 * 30, httpOnly: true, secure: false}
}))
// 设置日志格式
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'))
app.use(cookieParser())
app.use(express.query())
app.use(AV.express())
app.use('/test', routes.test)
app.use('/user', routes.user)

if (env === 'development') {
  const webpack = require('webpack')
  const swaggerJSDoc = require('swagger-jsdoc')
  const webpackConfig = require('./webpack.dev.config')
  const webpackBase = require('./webpack.base.config')
  const compiler = webpack(webpackConfig)
  app.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true,
    quiet: false,
    publicPath: webpackBase.output.publicPath,
    stats: {
      colors: true,
      chunks: false
    }
  }))
  app.use(require('webpack-hot-middleware')(compiler, {
    log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000
  }))
  // swagger doc definition
  const options = {
    swaggerDefinition: {
      info: {
        title: 'leancloud 测试项目', // Title (required)
        version: '1.0.0', // Version (required),
        schemes:'http'
      },
    },
    apis: ['./app/routes/*.js'], // Path to the API docs
  }

// Initialize swagger-jsdoc -> returns validated swagger spec in json format
  const swaggerSpec = swaggerJSDoc(options);
  app.get('/api-docs.json', function(req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.send(swaggerSpec);
  })
  app.use(express.static('swagger'));
 /* app.get('/swaggerui', (req, res) => {
    res.sendFile(path.resolve(__dirname, '.', 'swagger', 'index.html'))
  })*/
} else {
  app.use(expressStaticGzip(staticPath,{
    enableBrotli: true,
    customCompressions: [{
      encodingName: "deflate",
      fileExtension: "zz"
    }]
  }))

  app.use(express.static(path.resolve(__dirname, '.', staticPath)))

}

// 所有其他的地址交给前端路由进行处理
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '.', staticPath, 'index.html'))
})
app.listen(port, function (err) {
  if (err) {
    console.log(err)
    return
  }
  console.log(`Listening at ${port}`)
})
